package tbdp.tool.common;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by xbkaishui on 16/10/15.
 */
public class Utils {
    private static Logger log = Logger.getLogger(Utils.class);

    public static String generateFinalOut(String marketType, String date, String fileName) {
        if (StringUtils.equalsIgnoreCase(marketType, Constants.sh)) {
            return String.format("hdfs:/topcj/market/%s/T_O_SH/T_O_SH-%s", date, fileName);
        } else {
            return String.format("hdfs:/topcj/market/%s/T_O_SZ/T_O_SZ-%s", date, fileName);
        }
    }

    public static void executeCmd(String cmd, String workDir) {
        try {
//            ProcessBuilder pb = new ProcessBuilder(cmd);
//            pb.directory(new File(workDir));
//            Process p = pb.start();
            Process p = Runtime.getRuntime().exec(cmd);
            InputStream fis = p.getInputStream();
            System.out.println(IOUtils.toString(fis));
            p.waitFor();
        } catch (Throwable e) {
            log.error("exec cmd error", e);
        }

    }

    public static String reformatTime(String timeStr) {
        String time = StringUtils.leftPad(timeStr,6,'0');
        return time.substring(0, 2) + ":" + time.substring(2, 4) + ":" + time.substring(4);
    }


    /**
     * 检验字符串是否是数字形式 如果是 返回原字符串 否则返回0
     *
     * @param str
     * @return
     */
    public static String validNumber(String str) {
        try {
            Double.parseDouble(str);
        } catch (Throwable e) {
            return "0";
        }
        return str;
    }


    /**
     * 删除文件
     *
     * @param files
     */
    public static void deleteFiles(File... files) {
        for (File f : files) {
            FileUtils.deleteQuietly(f);
        }
    }

    /**
     * 删除文件 当程序退出的时候
     *
     * @param files
     */
    public static void deleteFilesOnExit(File... files) {
        for (File f : files) {
            try {
                FileUtils.forceDeleteOnExit(f);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        System.out.println(reformatTime("081229"));
    }

}
